<template>
	<view class="add-friend-container">
		<!-- 自定义顶部导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="nav-left" @tap="goBack">
					<u-icon name="arrow-left" size="20" color="#333"></u-icon>
				</view>
				<view class="nav-tabs">
					<view v-for="tab in tabs" :key="tab.key" class="nav-tab" :class="{ active: currentTab === tab.key }"
						@tap="switchTab(tab.key)">
						<text class="nav-tab-text">{{ tab.label }}</text>
						<view v-if="currentTab === tab.key" class="nav-tab-indicator"></view>
					</view>
				</view>
				<view class="nav-placeholder"></view>
			</view>
		</view>

		<view class="page-body">
			<!-- 添加好友 -->
			<view v-if="currentTab === 'add'" class="tab-panel">
				<!-- 搜索框 -->
				<view class="search-section">
					<view class="search-box">
						<u-icon name="search" size="18" color="#999"></u-icon>
						<input class="search-input" v-model="searchKeyword" placeholder="搜索用户名或邮箱"
							@input="onSearchInput" @confirm="handleSearch" />
						<view v-if="searchKeyword" class="clear-btn" @tap="clearSearch">
							<u-icon name="close" size="16" color="#999"></u-icon>
						</view>
					</view>
					<view v-if="showResults" class="result-summary">
						<text class="result-count">共 {{ searchTotal }} 个结果</text>
					</view>
				</view>

				<!-- 搜索结果列表 -->
				<scroll-view v-if="showResults" class="results-list" scroll-y>
					<view v-if="loading" class="loading-wrapper">
						<text class="loading-text">搜索中...</text>
					</view>
					<view v-else-if="searchResults.length > 0" class="results-content">
						<view v-for="user in searchResults" :key="user.id" class="user-item">
							<image class="user-avatar" :src="user.avatar || '/static/logo.png'" mode="aspectFill">
							</image>
							<view class="user-info">
								<text class="username">{{ user.username || '未设置用户名' }}</text>
								<text v-if="user.email" class="user-email">{{ user.email }}</text>
								<text v-if="user.bio" class="user-bio">{{ user.bio }}</text>
							</view>
							<view class="user-action">
								<view v-if="user.friendshipStatus === null" class="add-btn"
									@tap="handleAddFriend(user)">
									<text class="add-btn-text">添加</text>
								</view>
								<view v-else-if="user.friendshipStatus === FriendshipStatusEnum.PENDING"
									class="status-text pending">
									已发送
								</view>
								<view v-else-if="user.friendshipStatus === FriendshipStatusEnum.ACCEPTED"
									class="status-text accepted">
									已是好友
								</view>
								<view v-else-if="user.friendshipStatus === FriendshipStatusEnum.BLOCKED"
									class="status-text blocked">
									已拉黑
								</view>
							</view>
						</view>
					</view>
					<view v-else class="empty-state">
						<text class="empty-icon">🔍</text>
						<text class="empty-text">未找到相关用户</text>
					</view>
				</scroll-view>

				<!-- 空状态提示 -->
				<view v-else class="empty-hint">
					<text class="hint-text">输入用户名或邮箱搜索用户</text>
				</view>
			</view>

			<!-- 好友列表 -->
			<view v-else class="tab-panel">
				<view class="friend-search-section">
					<view class="search-box">
						<u-icon name="search" size="18" color="#999"></u-icon>
						<input class="search-input" v-model="friendSearchKeyword" placeholder="搜索好友昵称或邮箱"
							@input="onFriendSearchInput" />
						<view v-if="friendSearchKeyword" class="clear-btn" @tap="clearFriendSearch">
							<u-icon name="close" size="16" color="#999"></u-icon>
						</view>
					</view>
					<view class="result-summary" v-if="filteredFriendList.length || friendSearchKeyword">
						<text class="result-count">已匹配 {{ filteredFriendList.length }} 位好友</text>
					</view>
				</view>
				<scroll-view class="friend-list" scroll-y @scrolltolower="loadMoreFriends">
					<view v-if="friendLoading && friendList.length === 0" class="loading-wrapper">
						<text class="loading-text">加载中...</text>
					</view>
					<view v-else-if="filteredFriendList.length > 0" class="friends-content">
						<view v-for="friend in filteredFriendList" :key="friend.id" class="friend-item"
							@tap="openChatWithFriend(friend)">
							<image class="friend-avatar" :src="friend.avatar || '/static/logo.png'" mode="aspectFill">
							</image>
							<view class="friend-info">
								<text class="friend-name">{{ friend.username || `用户${friend.id}` }}</text>
								<text v-if="friend.email" class="friend-email">{{ friend.email }}</text>
							</view>
						</view>
					</view>
					<view v-else class="empty-state">
						<text class="empty-icon">👥</text>
						<text class="empty-text">
							{{ friendSearchKeyword ? '没有匹配的好友' : '暂时还没有好友' }}
						</text>
					</view>

					<view v-if="friendLoading && friendList.length > 0" class="loading-more">
						<text>加载更多...</text>
					</view>
					<view v-else-if="!friendLoading && !friendHasMore && friendList.length > 0" class="no-more">
						<text>没有更多了</text>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import {
	searchUsers,
	sendFriendRequest,
	getFriendsList,
	type SearchUserInfo,
	type FriendInfo,
	FriendshipStatus
} from '@/api/friends'

// 暴露枚举给模板使用
const FriendshipStatusEnum = FriendshipStatus

type TabKey = 'add' | 'list'

// 状态栏高度（自定义导航栏使用）
const statusBarHeight = ref(0)

onMounted(() => {
	const systemInfo = uni.getSystemInfoSync()
	statusBarHeight.value = systemInfo.statusBarHeight || 0
})

// 顶部Tab
const friendTotal = ref(0)
const tabs = computed(() => [
	{ key: 'add' as TabKey, label: '添加好友' },
	{
		key: 'list' as TabKey,
		label: friendTotal.value > 0 ? `好友列表(${friendTotal.value})` : '好友列表'
	}
])

const currentTab = ref<TabKey>('add')

// 搜索关键词
const searchKeyword = ref('')

// 是否显示搜索结果
const showResults = ref(false)

// 加载状态
const loading = ref(false)

// 搜索结果
const searchResults = ref<SearchUserInfo[]>([])
const searchTotal = ref(0)

// 搜索防抖定时器
let searchTimer: ReturnType<typeof setTimeout> | null = null

// 好友列表
const friendList = ref<FriendInfo[]>([])
const friendLoading = ref(false)
const friendPage = ref(1)
const friendLimit = 20
const friendHasMore = ref(true)
const friendListLoaded = ref(false)
const friendSearchKeyword = ref('')
const filteredFriendList = computed(() => {
	if (!friendSearchKeyword.value.trim()) {
		return friendList.value
	}
	const keyword = friendSearchKeyword.value.trim().toLowerCase()
	return friendList.value.filter(friend => {
		const username = friend.username?.toLowerCase() || ''
		const email = friend.email?.toLowerCase() || ''
		return username.includes(keyword) || email.includes(keyword)
	})
})

const goBack = () => {
	uni.navigateBack()
}

const switchTab = (key: TabKey) => {
	if (currentTab.value === key) return
	currentTab.value = key
	if (key === 'list' && !friendListLoaded.value) {
		loadFriendList()
	}
}

// 搜索输入
const onSearchInput = () => {
	if (searchTimer) {
		clearTimeout(searchTimer)
	}

	if (!searchKeyword.value.trim()) {
		showResults.value = false
		searchResults.value = []
		return
	}

	// 防抖：500ms后执行搜索
	searchTimer = setTimeout(() => {
		handleSearch()
	}, 500)
}

// 执行搜索
const handleSearch = async () => {
	const keyword = searchKeyword.value.trim()
	if (!keyword) {
		showResults.value = false
		searchResults.value = []
		searchTotal.value = 0
		return
	}

	loading.value = true
	showResults.value = true

	try {
		const response = await searchUsers(keyword, 1, 20)
		searchResults.value = response.data.data
		searchTotal.value = response.data.total
	} catch (error: any) {
		console.error('搜索用户失败:', error)
		uni.showToast({
			title: error.message || '搜索失败',
			icon: 'none'
		})
		searchResults.value = []
		searchTotal.value = 0
	} finally {
		loading.value = false
	}
}

// 清空搜索
const clearSearch = () => {
	searchKeyword.value = ''
	showResults.value = false
	searchResults.value = []
	searchTotal.value = 0
	if (searchTimer) {
		clearTimeout(searchTimer)
		searchTimer = null
	}
}

// 添加好友
const handleAddFriend = async (user: SearchUserInfo) => {
	try {
		await sendFriendRequest({
			friendId: user.id
		})

		uni.showToast({
			title: '好友请求已发送',
			icon: 'success'
		})

		// 更新用户状态
		const index = searchResults.value.findIndex(u => u.id === user.id)
		if (index !== -1) {
			searchResults.value[index].friendshipStatus = FriendshipStatus.PENDING
		}
	} catch (error: any) {
		console.error('发送好友请求失败:', error)
		uni.showToast({
			title: error.message || '发送失败',
			icon: 'none'
		})
	}
}

// 获取好友列表
const loadFriendList = async (isLoadMore: boolean = false) => {
	if (friendLoading.value) return
	if (isLoadMore && !friendHasMore.value) return

	friendLoading.value = true
	try {
		const currentPage = isLoadMore ? friendPage.value + 1 : 1
		const response = await getFriendsList(currentPage, friendLimit)
		const list = response.data.data || []

		if (isLoadMore) {
			friendList.value = friendList.value.concat(list)
			friendPage.value = currentPage
		} else {
			friendList.value = list
			friendPage.value = 1
		}

		friendTotal.value = response.data.total || list.length
		friendHasMore.value = list.length >= friendLimit
		friendListLoaded.value = true
		friendSearchKeyword.value = ''
	} catch (error: any) {
		console.error('获取好友列表失败:', error)
		uni.showToast({
			title: error.message || '加载失败',
			icon: 'none'
		})
		if (!isLoadMore) {
			friendList.value = []
			friendHasMore.value = false
		}
	} finally {
		friendLoading.value = false
	}
}

const loadMoreFriends = () => {
	if (friendLoading.value || !friendHasMore.value) return
	loadFriendList(true)
}

const onFriendSearchInput = () => {
	// computed handles filtering
}

const clearFriendSearch = () => {
	friendSearchKeyword.value = ''
}

const openChatWithFriend = (friend: FriendInfo) => {
	uni.navigateTo({
		url: `/pages/chat/chat?userId=${friend.id}`
	})
}

onLoad((options) => {
	const tabKey = (options?.tab || '') as TabKey
	if (tabKey === 'list') {
		currentTab.value = 'list'
		if (!friendListLoaded.value) {
			loadFriendList()
		}
	}
})
</script>

<style scoped>
.add-friend-container {
	width: 100%;
	height: 100vh;
	background-color: #f5f5f5;
	display: flex;
	flex-direction: column;
}

.custom-navbar {
	background-color: #fff;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
	position: sticky;
	top: 0;
	z-index: 10;
}

.navbar-content {
	height: 88rpx;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
}

.nav-left,
.nav-placeholder {
	width: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.nav-tabs {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: flex-end;
	gap: 40rpx;
}

.nav-tab {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-bottom: 10rpx;
}

.nav-tab-text {
	font-size: 30rpx;
	color: #999;
}

.nav-tab.active .nav-tab-text {
	color: #333;
	font-weight: 600;
}

.nav-tab-indicator {
	width: 40rpx;
	height: 6rpx;
	background-color: #4A90E2;
	border-radius: 999rpx;
	margin-top: 8rpx;
}

.page-body {
	flex: 1;
	display: flex;
	flex-direction: column;
	padding: 0 0 20rpx;
}

.tab-panel {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.result-summary {
	padding: 10rpx 30rpx 0;
}

.result-count {
	font-size: 24rpx;
	color: #999;
}

/* 搜索区域 */
.search-section {
	background-color: #fff;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.search-box {
	display: flex;
	align-items: center;
	background-color: #f5f5f5;
	border-radius: 40rpx;
	padding: 20rpx 30rpx;
	gap: 15rpx;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

.clear-btn {
	width: 32rpx;
	height: 32rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 搜索结果列表 */
.results-list {
	flex: 1;
	min-height: 0;
	overflow-y: auto;
	margin-top: 20rpx;
}

.loading-wrapper {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
}

.results-content {
	background-color: #fff;
}

.user-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	gap: 20rpx;
}

.user-avatar {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #f0f0f0;
}

.user-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.username {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
}

.user-email {
	font-size: 24rpx;
	color: #999;
}

.user-bio {
	font-size: 24rpx;
	color: #666;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.user-action {
	display: flex;
	align-items: center;
}

.add-btn {
	padding: 12rpx 30rpx;
	background-color: #4A90E2;
	border-radius: 40rpx;
}

.add-btn-text {
	font-size: 26rpx;
	color: #fff;
}

.status-text {
	font-size: 24rpx;
	padding: 12rpx 20rpx;
	border-radius: 40rpx;
}

.status-text.pending {
	color: #ff9500;
	background-color: #fff5e5;
}

.status-text.accepted {
	color: #4A90E2;
	background-color: #e5f3ff;
}

.status-text.blocked {
	color: #999;
	background-color: #f5f5f5;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 200rpx 0;
	gap: 20rpx;
}

.empty-icon {
	font-size: 100rpx;
	opacity: 0.5;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.friend-list {
	flex: 1;
	min-height: 0;
	overflow-y: auto;
}

.friend-search-section {
	background-color: #fff;
	padding: 20rpx 30rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.friends-content {
	background-color: #fff;
}

.friend-item {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	gap: 20rpx;
}

.friend-avatar {
	width: 96rpx;
	height: 96rpx;
	border-radius: 50%;
	background-color: #f0f0f0;
}

.friend-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.friend-name {
	font-size: 32rpx;
	color: #000;
	font-weight: 600;
}

.friend-email {
	font-size: 22rpx;
	color: #999;
}

.friend-bio {
	font-size: 24rpx;
	color: #666;
}

.loading-more,
.no-more {
	text-align: center;
	padding: 20rpx 0;
	font-size: 24rpx;
	color: #999;
}

.empty-hint {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}

.hint-text {
	font-size: 28rpx;
	color: #999;
}
</style>
